package com.clpms.utils;

import com.clpms.bean.enumBean.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 *
 * @author caixinyong
 * @date 2023/2/16 4:34 PM
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

	@ExceptionHandler(Exception.class)
	public ResultDto handleThrowable(Exception e, HttpServletRequest request) {
		if (e instanceof CommonException) {
			CommonException exception = (CommonException) e;
			log.error("发生异常了,系统已知异常,url:{},msg:{}",
					request.getRequestURI(),
					String.format("code:%s,msg:%s,data:%s", exception.getCode(), exception.getMsg(), exception.getData()),
					exception);
			return ResultDto.Fail(exception.getCode(), exception.getMsg(), exception.getData());
		}
		log.error("发生异常了,系统未知异常,url:{}", request.getRequestURI(), e);
		return ResultDto.Fail(ErrorCodeEnum.SYSTEM_ERROR);

	}

	@ExceptionHandler(BindException.class)
	public ResultDto exceptionHandler(BindException e, HttpServletRequest request) {
		String failMsg = e.getBindingResult().getFieldError().getDefaultMessage();
		ResultDto error = ResultDto.Fail(ErrorCodeEnum.PARAM_ERROR.getCode(), failMsg, failMsg);
		return error;
	}
}
